﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using nSL.QR;
using nSL.Libs;

using AForge.Video.DirectShow;
using AForge.Imaging;
using System.Drawing;
using System.Windows.Interop;
using System.Windows.Threading;
using nSL.Config;
using Dolinay;

namespace nSL.UC
{
    /// <summary>
    /// Interaction logic for WhoRU.xaml
    /// </summary>
    public partial class WhoRU : UserControl
    {
        public WhoRU()
        {
            InitializeComponent();
            camControl = new CamControl();
            dvList = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            Application.Current.Exit += new ExitEventHandler(Current_Exit);
            comboBox1.SelectedIndex = 0;
            if (ddt == null)
            {
                ddt = new DriveDetector();
                ddt.DeviceArrived += new DriveDetectorEventHandler(ddt_DeviceArrived);
            }
        }
        DriveDetector ddt = null;
        string currentDrive;
        void ddt_DeviceArrived(object sender, DriveDetectorEventArgs e)
        {
            MessageBox.Show("det");
            currentDrive = e.Drive;
            txtUser.Password = USBKey.ReadTokenFile(e.Drive);
            //RoutedEventArgs miss = null;
            RoutedEventArgs miss = null;
            btLogin_Click(sender, miss);
        }

        void Current_Exit(object sender, ExitEventArgs e)
        {

        }

        void process_ResultFound(object sender, ProcessArgs e)
        {
            //throw new NotImplementedException();
            txtUser.Dispatcher.Invoke(new Action(delegate()
            {
                txtUser.Password = e.Result;
                if (camControl.SelectedDevice.IsRunning)
                {
                    camControl.SelectedDevice.SignalToStop();
                }
                //RoutedEventArgs miss = null;
                RoutedEventArgs miss = null;
                btLogin_Click(sender, miss);
            }));
            if (camControl.SelectedDevice.IsRunning)
            {
                camControl.SelectedDevice.SignalToStop();
            }
            process.Stop();
        }

        FilterInfoCollection dvList;
        QRProcess process;
        CamControl camControl;

        //Reference the GDI DeleteObject method.
        [System.Runtime.InteropServices.DllImport("GDI32.dll")]
        public static extern bool DeleteObject(IntPtr objectHandle);

        private void btLogin_Click(object sender, RoutedEventArgs e)
        {
            string value = "";
            txtUser.Dispatcher.Invoke(new Action(delegate()
            {
                value = txtUser.Password.Trim();
                txtUser.Clear();
            }));
            if (value != Common.EXIT_CODE)
            {
                #region do something
                //--login here
                if (nSLLibs.Login(value))
                {
                    //write new key to token
                    ddt.DeviceArrived -= ddt_DeviceArrived;
                    //USBKey.WriteNewTokenFile(currentDrive, value);
                    //end login and open course--
                    UC.Splash sp = new Splash();
                    UC.Course course = new Course();
                    WpfPageTransitions.PageTransition transition = new WpfPageTransitions.PageTransition();
                    transition.TransitionType = WpfPageTransitions.PageTransitionType.Slide;
                    transition.ShowPage(course);
                    Window.GetWindow(this).Content = transition;

                    if (camControl.SelectedDevice.IsRunning)
                    {
                        camControl.SelectedDevice.SignalToStop();
                    }
                }
                else
                {
                    Message.Info(cString.ID("login.fail"));
                }
                #endregion
            }
            else if (value == Common.EXIT_CODE)
            {
                if (camControl.SelectedDevice.IsRunning)
                {
                    camControl.SelectedDevice.SignalToStop();
                }
                //Window.GetWindow(this).Close();
                Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                Application.Current.Shutdown();
            }
        }

        private void qrScan_Click(object sender, RoutedEventArgs e)
        {
            process = new QRProcess();
            process.ResultFound += new EventHandler<ProcessArgs>(process_ResultFound);
            process.Start();

            if (dvList.Count > 0)
            {

                if (camControl.SelectedDevice.IsRunning)
                {
                    camControl.SelectedDevice.SignalToStop();
                }

                camControl.SetCamera(0);
                camControl.SelectedDevice.NewFrame += new AForge.Video.NewFrameEventHandler(SelectedDevice_NewFrame);

                camControl.SelectedDevice.Start();
            }
            else
            {
                cMessage msg = new cMessage(cString.ID("error.no_device"), cMessage.BUTTON_TYPE.OK);
                msg.ShowDialog();
            }
        }

        void SelectedDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            //throw new NotImplementedException();
            using (UnmanagedImage uimage = UnmanagedImage.FromManagedImage(eventArgs.Frame))
            {
                try
                {
                    using (Bitmap image = uimage.ToManagedImage())
                    {
                        IntPtr hBitMap = image.GetHbitmap();
                        try
                        {
                            BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                            bmaps.Freeze();
                            Dispatcher.Invoke((Action)(() =>
                            {
                                imgUser.Source = bmaps;
                            }), DispatcherPriority.Render, null);
                            process.NewBitmap(image);
                        }
                        finally
                        {
                            DeleteObject(hBitMap);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
        }

        void processor_NewTargetPosition(System.Drawing.Bitmap image)
        {
            IntPtr hBitMap = image.GetHbitmap();
            BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            bmaps.Freeze();

            Dispatcher.Invoke((Action)(() =>
            {
                imgUser.Source = bmaps;
            }), DispatcherPriority.Render, null);
        }

        private void WhoRU_Unloaded(object sender, RoutedEventArgs e)
        {


        }

        private void txtUser_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                RoutedEventArgs miss = null;
                btLogin_Click(sender, miss);
            }
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            System.Windows.Controls.ComboBoxItem sel = (System.Windows.Controls.ComboBoxItem)comboBox1.SelectedItem;
            switch (sel.Content.ToString())
            {
                case "EN": Common.CURRENT_LANGUAGE = Common.Lang.Eng;
                    break;
                case "TH": Common.CURRENT_LANGUAGE = Common.Lang.Tha;
                    break;
                default: Common.CURRENT_LANGUAGE = Common.Lang.Tha;
                    break;
            }
        }
    }
}
